import urllib.parse
import oss2
from oss2.models import LiveChannelInfo, LiveChannelInfoTarget

from HuaXianGuan import settings
from common.config.config import PUBLIC
from common.utils.utils import date2timestamp, replace_double_slash

access_key_id = "LTAI5tB4SRQak2Ljwuyq1U5L"
access_key_secret = "sq5Bf9sKxISjvnrkeLV3aYSNR2UQAp"

bucket_name = "flower-1"

endpoint = "oss-cn-shanghai.aliyuncs.com"


class FileOss(object):
    """
    阿里云文件上传
    """

    def __init__(self):
        for param in (access_key_id, access_key_secret, bucket_name, endpoint):
            assert '<' not in param, '请设置参数：' + param
        # 创建Bucket对象，所有Object相关的接口都可以通过Bucket对象来进行
        self.bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name)

    def put_object(self, ali_path, local_path):
        """
        上传
        @param ali_path:
        @param local_path:
        @return:
        """
        result = self.bucket.put_object(ali_path, local_path)
        if result.status != 200:
            return
        download_link = PUBLIC['oss_url'] + "/" + ali_path
        download_link = replace_double_slash(download_link)
        return download_link

    def get_oss_image_url(self, ali_path, image_data):
        """
        下载图片
        @param ali_path:
        @param image_data:
        @return:
        """
        result = self.bucket.put_object(ali_path, image_data)
        if result.status != 200:
            return
        download_link = PUBLIC['oss_url'] + "/" + ali_path
        download_link = replace_double_slash(download_link)
        return download_link

    def down_object(self, ali_path, local_path):
        """
        下载到本地文件
        @param ali_path:
        @param local_path:
        @return:
        """
        self.bucket.get_object_to_file(ali_path, local_path)

    def del_object(self, ali_path):
        """
        删除
        @param ali_path:
        @return:
        """
        self.bucket.delete_object(ali_path)

    def review_file(self, oss_path):
        """
        设置样式，样式中包含文档预览参数。
        @param oss_path:
        @return:
        """
        style = 'imm/previewdoc,copy_1'
        # 将图片缩放为固定宽高100 px后，再旋转90°。
        # style = 'image'
        # 生成带签名的URL，并指定过期时间为10分钟。过期时间单位为秒。
        url = self.bucket.sign_url('GET', oss_path, 10 * 60, params={'x-oss-process': style})
        return f"{url}"

    def get_oss_plug_flow_url(self, channel_name):
        """
        获取视频流推送 url
        @param ali_path:
        @param image_data:
        @return:
        """
        channel_cfg = LiveChannelInfo(target=LiveChannelInfoTarget())
        # #查看channel状态
        result = self.bucket.list_live_channel("channel")
        channels = result.channels
        for channel in channels:
            name = channel.name
            publish_url = channel.publish_url
            if name == channel_name:
                return publish_url
        channel = self.bucket.create_live_channel(channel_name, channel_cfg)
        publish_url = channel.publish_url
        return publish_url

    def get_vod_play_url(self, channel_name, s_time, e_time):
        """
        生成播放列表
        """
        oss_url = getattr(settings, 'oss_url', '')
        try:
            start_time = date2timestamp(s_time)
            end_time = date2timestamp(e_time)
            playlist = "{}_{}.m3u8".format(s_time.replace(" ", "_"), e_time.replace(" ", "_"))
            result = self.bucket.post_vod_playlist(channel_name, playlist, start_time=start_time, end_time=end_time)
            play_url = "{}/{}/{}".format(oss_url, channel_name, playlist)
            return play_url
        except Exception as e:
            return ""

    def copy_file_to_path(self, source_key: str, target_key: str):
        """
        阿里云内复制文件
        @param source_key: 'path/to/source_file.jpg'  # 原始文件路径
        @param target_key: 'path/to/target_file.jpg'  # 目标文件路径
        @return:
        """
        self.bucket.copy_object(bucket_name, urllib.parse.unquote(source_key), target_key)

    def object_exists(self, ali_path):
        return self.bucket.object_exists(ali_path)

    def init_oss(self):
        return self.bucket

    def get_file(self, file_path: str):
        """获取文件"""
        file_path = urllib.parse.unquote(file_path)
        if self.object_exists(file_path):
            return self.bucket.get_object(file_path).read()